<template >
  <div class="report-container" style="opacity: 0.85;">
    <div class="report-title" >
      <h2>商品浏览次数Top-10</h2>
    </div>
    <div ref="chart" class="chart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import * as echarts from 'echarts';

const chart = ref(null);

const fetchAllLooks = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/products/allLooks');
    return response.data;
  } catch (error) {
    console.error('Error fetching looks:', error);
    return [];
  }
};

const processLookData = (data) => {
  const productCountMap = new Map();

  data.forEach(look => {
    const itemName = look.itemName;
    if (productCountMap.has(itemName)) {
      productCountMap.set(itemName, productCountMap.get(itemName) + 1);
    } else {
      productCountMap.set(itemName, 1);
    }
  });

  const productCountArray = Array.from(productCountMap, ([itemName, viewCount]) => ({ itemName, viewCount }));
  productCountArray.sort((a, b) => b.viewCount - a.viewCount);

  // 只返回前10个商品
  return productCountArray.slice(0, 10);
};

const initChart = (data) => {
  const chartInstance = echarts.init(chart.value);

  const option = {
    title: {
      text: '商品浏览次数Top-10',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.itemName),
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '浏览次数',
        type: 'bar',
        data: data.map(item => item.viewCount)
      }
    ]
  };

  chartInstance.setOption(option);
};

onMounted(async () => {
  const looksData = await fetchAllLooks();
  const rankingData = processLookData(looksData);
  initChart(rankingData);
});
</script>

<style scoped>
.report-container {
  background-color: rgb(246, 247, 245);
  padding: 20px;
  border-radius: 10px;
  text-align: center;
}

.report-title {
  font-size: 2em;
  margin-bottom: 20px;
  text-transform: capitalize;
  color: #aaa;
  text-shadow:
    -1px -1px 1px #aaa,
    0px 2px 1px rgba(0, 0, 0, 0.5),
    2px 2px 2px rgba(0, 0, 0, 0.7),
    0px 0px 3px rgba(0, 0, 0, 0.4);
  text-align: center;
}

.chart {
  width: 100%;
  height: 500px;
}
</style>
